package sk.tuke.android4all.messenger;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnGenericMotionListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.TextView;
import sk.tuke.android4all.controls.CustomFragment;
import sk.tuke.android4all.listeners.SwipeListener;
import sk.tuke.android4all.services.Tts;

public class SentMessagesFragment extends CustomFragment{

	private static String TAG = "ReceivedMessagesFragment";
	private Activity mActivity = null;
	private int selectedTag = 0;
	int touchCounter = 0;
	private final int TOUCH_INTENSITY = 4;
	private SwipeListener mActionListener = null;
	private Tts mSpeechEngine;
	private CollectionHelper mCollectionHelper = null;
	private HashMap<Integer, Message> messagesMapping;
		
	public SentMessagesFragment(Activity aActivity_in){
		mActivity = aActivity_in;
		selectedTag = 0;
		mSpeechEngine = new Tts(mActivity);
		mCollectionHelper = new CollectionHelper<Message>(new SMSHelper(mActivity).getOutboxMessages(), 5);
		messagesMapping = new HashMap<Integer, Message>();
	}
	
	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_receiver, container, false);	       
        return rootView;
    }
	
	@Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        createUI();
    }
	
	private void createUI() {
		mActionListener = new SwipeListener(this.mActivity) {
	        @Override
	        public void onDoubleTapAction(int count) {
	            Log.i("TAG", "DoubleTapped " + selectedTag);
	            resetTouchCounter();
	            if(selectedTag != 0){
	            	FragmentTransaction f = mActivity.getFragmentManager().beginTransaction();
	            	if(selectedTag == R.id.next){
	            		loadNextMessages();
	            	}else{
	            		mSpeechEngine.sayMessage(getResources().getString(R.string.message_intro));
	            		Message m = messagesMapping.get(selectedTag);
	            		Intent extras = new Intent("sk.tuke.android4all.smsview");
	            		extras.putExtra("from", m.getFrom());
	            		extras.putExtra("date", m.getTimestamp());
	            		extras.putExtra("message", m.getText());
	            		mActivity.startActivity(extras);
	            	}
	            }
	        }

			@Override
			public void onZoomInAction() {
				// TODO Auto-generated method stub
				 
			}

			@Override
			public void onZoomOutAction() {
				// TODO Auto-generated method stub
				
			}
		};
		
		getView().setOnTouchListener(mActionListener);
		loadNextMessages();
		
		
		final TextView nextMessages = (TextView) getView().findViewById(R.id.next);	
		nextMessages.setOnGenericMotionListener(new OnGenericMotionListener(){

			@Override
			public boolean onGenericMotion(View arg0, MotionEvent event) {
				mActionListener.resetTouchCounter();
				String textInControl = nextMessages.getText().toString();
                if (selectedTag != R.id.next && touchCounter>TOUCH_INTENSITY) {
                    touchCounter = 0;
                    mSpeechEngine.sayMessage(textInControl);
                    selectedTag = R.id.next;
                }else{
                    touchCounter++;
                }
                return false;
			}});
	}
	
	@Override
	public void returnAction() {
		mActivity.finish();
	}

	private void loadNextMessages() {
		List<Message> messages = mCollectionHelper.getNext();
		LinearLayout container = (LinearLayout) getView().findViewById(R.id.messages_container);
		container.removeAllViews();
		container.setWeightSum(messages.size());
		messagesMapping.clear();
		
		LayoutInflater inflater = (LayoutInflater)mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		
		int identifier = 1;
		for(final Message m : messages){
			final LinearLayout messageControls = (LinearLayout)inflater.inflate(R.layout.fragment_message, null);
			android.widget.LinearLayout.LayoutParams params = new android.widget.LinearLayout.LayoutParams(
		            LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 1f);
			messageControls.setLayoutParams(params);
			TextView from = (TextView)messageControls.findViewById(R.id.message_from);
			TextView date = (TextView)messageControls.findViewById(R.id.message_datetime);
			TextView text = (TextView)messageControls.findViewById(R.id.message_preview);
			
			from.setText(m.getFrom());
			date.setText(new Date(m.getTimestamp()).toString());
			text.setText( SMSHelper.getPreviewText(m.getText()));
			final int id = identifier;
			
			messageControls.setOnGenericMotionListener(new OnGenericMotionListener() {

				@Override
				public boolean onGenericMotion(View arg0, MotionEvent arg1) {
					Log.i(TAG, "Selected tag: " + selectedTag);
					mActionListener.resetTouchCounter();
					String textInControl = "From " + m.getFrom() + ". Date: " +new Date(m.getTimestamp()).toString()+
							SMSHelper.getPreviewText(m.getText());
	                if (selectedTag != id && touchCounter>TOUCH_INTENSITY) {
	                    touchCounter = 0;
	                    mSpeechEngine.sayMessage("SMS: " + SMSHelper.getPreviewText(m.getText()));
	                    
	                    selectedTag = id;
	                }else{
	                    touchCounter++;
	                }
					return false;
				}});
			container.addView(messageControls);
			messagesMapping.put(id, m);
			identifier++;
		}
	}
	
	@Override
	public void proceedReturnedResult(int requestCode, int resultCode, Intent in){
		Log.i(TAG, "proceedReturnedResult");
	 	//((TextView)getView().findViewById(requestCode)).setText(in.getExtras().getString("text"));
    }
	
}
